<template>
  <div class="rechargeModal">
    <a-modal :width="1180" :visible="visible" @cancel="handleClose" :footer="null" :destroyOnClose="true" centered
    :zIndex="1007" :maskClosable="false" :bodyStyle="{ maxHeight: '600px', overflow: 'auto' }">
      <template #title>
        <div class="title">
          <span class="font-bold">选择{{ unitName }}包</span>
          <span>（购买后立即生效）</span>
        </div>
      </template>
      <div class="package-list">
        <div class="package-item" v-for="(item, index) in packageList" :key="index"
          :class="currentPackage?.id == item?.id ? 'active' : ''" @click="packageChange(item)">
          <div class="item-content">
            <div class="point">
              <!-- <thunderbolt-filled class="point-icon" /> -->
              <span class="fs-18"> {{ item.point_number }}</span>
              <span>{{ unitName }}</span>
            </div>
            <div class="price">
              <span class="money-icon">￥</span>
              <span>{{ item.price }}</span>
            </div>
          </div>
          <div class="item-bottom">
            <!-- <template v-if="item.give_point_number"> -->
            <span class="give-item-icon">赠送</span>
            <div class="name">
              {{ item.give_point_number }}{{ unitName }}
            </div>
            <!-- </template> -->
            <!-- <div v-else>立即充值</div> -->
          </div>
        </div>
      </div>
      <div class="pay-area">
        <div class="pay-qr-code">
          <a-image :preview="false" style="width: 110px; height: 110px" :src="payQrCodeUrl" :fallback="contact_url">
          </a-image>
        </div>
        <div class="pay-content-area">
          <div class="pay-moneny-area">
            <span class="momey-label">应付金额：</span>
            <span class="momey-value" v-if="allowBtn">￥{{ currentPackage?.price ?? 0 }}</span>
            <span v-else style="color: red">{{ disbledTxt }}</span>

          </div>
          <div class="pay-type">
            <div class="methods_tab">
              <span class="momey-label">支持支付方式：</span>
              <div class="methods_item" v-for="(item, index) in payMethods" :key="index">
                <img :src="item.icon" style="
                      width: 18px;
                      height: 18;
                      border-radius: 10px;
                      overflow: hidden;
                    " alt="" />
                <div>{{ item.tab_name }}</div>
              </div>
            </div>
          </div>
          <div class="pay-tip">
            过期算力将失效，续费后会激活之前剩余算力
          </div>
          <div class="pay-bottom" @click="vipVisible = true">
            <div class="user-agreement">支付即视为您同意</div>
            <div class="user-link">《会员服务协议》</div>
          </div>
        </div>
      </div>
      <ProtocolModal :visible="vipVisible" titleTxt="会员服务协议" :content="pay_agreement_url" @onClose="vipVisible = false">
      </ProtocolModal>
    </a-modal>
  </div>
</template>
<script setup>
import { watch, ref, reactive, onMounted, computed } from "vue";
import request from "@/common/utils/request";
import { ThunderboltFilled } from "@ant-design/icons-vue";
import utils from "@/common/utils/utils";
import store from "@/store";
import ProtocolModal from "@/components/ProtocolModal/Index.vue";
import weixinIcon from "@/common/image/weixin_icon.png";
import alipayIcon from "@/common/image/alipay_icon.png";
import { message } from "ant-design-vue";
let emits = defineEmits(["close", "success"]);
let props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
});
let packageList = ref([]);
let currentPackage = ref({
  id: 0,
  payUrl: "",
  name: "",
  content: [],
  money: 0,
  point_coin: {
    alias: "积分",
  },
});
let unitName = ref("");
let allowBtn = ref(true);
let disbledTxt = ref("");
let loading = ref(false);
let payUrl = ref("");
let payQrCodeUrl = ref("");
let vipVisible = ref(false);
let pay_agreement_url = ref("");
let payMethods = [
  {
    tab_name: "微信支付",
    icon: weixinIcon,
    tab_id: 0,
  },
  {
    tab_name: "支付宝",
    icon: alipayIcon,
    tab_id: 0,
  },
];
let contact_url = ref("");
let checkPayTimer = ref(null)
const getPackageList = () => {
  request
    .get("/work_ai", "/user/socialMedia/pointCoinPackage/get")
    .then((res) => {
      unitName.value = res.alias;
      packageList.value = res.list;

      allowBtn.value = res.prompt.status;
      disbledTxt.value = res.prompt.msg;
      if (allowBtn.value) {
        if (packageList.value.length > 0) {
          currentPackage.value = packageList.value.find(
          (item) => item.price != 0
          );
       }
        getPayInfo();
      }
    });
};
const getPayInfo = async() => {
  if(checkPayTimer.value){
    clearInterval(checkPayTimer.value);
  }

  const villageInfo = await store.dispatch("GetVillageInfo");
  let params = {
    id: currentPackage.value.id,
    village_id: villageInfo ? villageInfo.id : 0,
  };
  loading.value = true;
  request
    .post("/work_ai", "/user/socialMedia/pointCoinPackage/pay", params)
    .then((res) => {
      loading.value = false;
      // console.log(res);

      // if (res?.result?.pay_status === "success") {
      //     router.push({ name: "MediaBusinessRecord" });
      //     message.success("操作成功");
      //     return;
      // }
      if (res?.result?.pay_status === "loading") {
        payUrl.value = res?.result?.pay_url;
        getQrCodeUrl(payUrl.value);
      }
    })
    .catch(() => {
      loading.value = false;
    });
};
const getConfig = () => {
  request.get("/work_ai", "/config").then((res) => {
    if (res.list && res.list.pay_agreement_url) {
      pay_agreement_url.value = res.list.pay_agreement_url;
    }
    if (res.list && res.list.service_qrcode) {
      contact_url.value = res.list.service_qrcode;
    }
  });
};
const getQrCodeUrl = (qrCode) => {
  let params = {
    qrCode,
  };
  request.get("/public", "/qrcode", params).then((result) => {
    payQrCodeUrl.value = result.url;
    const params = new URLSearchParams(qrCode);
    const orderId = params.get("tmp_order_id");
    checkPayHandle(orderId);
  });
};
const checkPayHandle = (order_id) => {
  checkPayTimer.value = setInterval(() => {
    request
      .get("/work_ai", "/order/shotstack/getOrderStatus", {
        order_id: order_id,
      })
      .then((checkResult) => {
        if (checkResult.status == 4) {
          message.error("订单超时已取消");
          clearInterval(checkPayTimer.value);
          currentPackage.value.id && getPayInfo();
        } else if (checkResult.status == 1) {
          clearInterval(checkPayTimer.value);
          store.dispatch("GetVersionInfo");
          message.success("支付成功");
          handleClose();
          emits("success");
        }
      });
  }, 2000);
};

const packageChange = (item) => {
  if (currentPackage.value.id == item.id) {
    return;
  }
  if (item.price == 0 || !allowBtn.value) {
    return message.warning("当前套餐不支持充值");
  }
  currentPackage.value = item;
  getPayInfo();
};
const handleClose = () => {
  emits("close");
};
watch(
  () => props.visible,
  (val) => {
    if (val) {
      getPackageList();
      getConfig();
    } else {
      clearInterval(checkPayTimer.value);
    }
  }
);
</script>
<style lang="less" scoped>
.package-list {
  width: 100%;
  display: flex;
  flex-wrap: nowrap;
  gap: 15px;
  margin-top: 20px;
  height: 220px;
  overflow-x: auto;
}
.package-item {
  width: 170px;
  height: 205px;
  display: flex;
  flex-shrink: 0;
  flex-direction: column;
  justify-content: space-between;
  border: 1px solid #d9d9d9;
  border-radius: 10px;
  cursor: pointer;
}
.item-content {
  flex: 1;
}
.point {
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--ss-primary-color);
  margin-top: 20px;
  font-size: 16px;
}

.point-icon {
  color: #72c23d;
  margin-right: 2px;
  margin-top: 4px;
}
.money-icon {
  font-size: 14px;
}
.price {
  font-size: 28px;
  font-weight: 600;
  text-align: center;
  margin-top: 50px;
}
.item-bottom {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 5px 20px;
  background-color: #f7f8fc;
  border-radius: 0 0 10px 10px;
  color: #333;
}
.active {
  border: 2px solid var(--ss-primary-color);
  .item-bottom {
    background-color: var(--ss-primary-color);
    color: #fff;
    border-radius: 0 0 7px 7px;
  }
}
.give-item-icon {
  background-color: #fcdcdd;
  color: #e75767;
  font-size: 14px;
  margin-right: 10px;
  padding: 0 2px;
  border-radius: 2px;
}
.pay-area {
  display: flex;
  gap: 10px;
  margin-top: 22px;
  padding: 34px 20px;
  background-color: #f9f9fa;
  border-radius: 20px;
  .pay-qr-code {
    img {
      width: 110px;
      height: 110px;
    }
  }
  .pay-content-area {
    display: flex;
    flex-direction: column;
    gap: 5px;
    .methods_tab {
      display: flex;
      align-items: center;
      font-size: 14px;
      .methods_item {
        // width: 116px;
        // height: 34px;
        // border: 2px solid #dfdfdf;
        border-radius: 5px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 5px;
        cursor: pointer;

        &:nth-child(1) {
          margin-left: 0;
        }

        &.pay_active {
          border: 0;
          background-image: url("@/common/image/pay_selected.png");
          background-repeat: no-repeat;
          background-size: 100% 100%;
        }
      }
    }
    .pay-type {
      // margin: 5px 0 22px 0;
    }
    .pay-moneny-area {
      display: flex;
      // line-height: 38px;
      align-items: center;
      // margin: 8px 0;
      .momey-label {
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #999999;
      }
      .momey-value {
        font-size: 24px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #f2372e;
        // margin-left: 10px;
      }
      .discount {
        background-color: #f9e6e6;
        color: #f2372e;
        padding: 2px 10px;
        border-radius: 2px;
        font-size: 14px;
        margin-left: 10px;
      }
    }
    .pay-tip{
      color: #f2372e;
    }
    .pay-bottom {
      display: flex;
      cursor: pointer;
      .user-agreement {
        color: var(--ss-primary-color);
      }
      .user-link {
        color: #ffa500;
      }
    }
  }
}
</style>
